
<%@page import="com.nescafe.nescafepromo.util.FormatUtil"%>
<%@page import="com.nescafe.nescafepromo.entity.TotalPoints"%>
<%@page import="com.nescafe.nescafepromo.entity.Participant"%>
<%@page import="com.google.appengine.api.datastore.Entity"%>
<%@page import="java.util.List"%>
<%@page import="com.nescafe.nescafepromo.controller.UserController"%>
<%@page import="com.nescafe.nescafepromo.model.NPResponse"%>
<%@page import="com.nescafe.nescafepromo.controller.Controller"%>
<%@page import="com.google.gson.Gson"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.net.URL"%>
<%@page import="com.nescafe.nescafepromo.model.MainPageInfo"%>
<%@page import="com.nescafe.nescafepromo.model.FBResponse"%>
<%@page import="com.nescafe.nescafepromo.model.NPRequest"%>
<%@page import="com.nescafe.nescafepromo.command.CommandType"%>
<%@page import="com.nescafe.nescafepromo.model.SignedRequest"%>
<%@page import="com.nescafe.nescafepromo.NescafePromo"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	//http://developers.facebook.com/docs/authentication/canvas/
	//String code = request.getParameter("code");
	String sReqStr = request.getParameter("signed_request");
	//code = "DELETE THIS LATER";
	if (sReqStr == null || sReqStr.isEmpty()) {
		String authUrl = NescafePromo.get().getFBAuthService().getAuthorizationUrl(null);
		response.sendRedirect(authUrl + "&scope=email,user_location,publish_stream,publish_actions");		
	} else {
		SignedRequest signedRequest = new SignedRequest(sReqStr);
		NPRequest npReq = new NPRequest(request,CommandType.GET_MAIN_PAGE_INFO);
		FBResponse fbResponse = null;
		MainPageInfo mainPageInfo = null;
		if(!signedRequest.isAuthorized()){
			String error = request.getParameter("error");
			if(error==null || error.isEmpty()){
				String authUrl = NescafePromo.get().getFBAuthService().getAuthorizationUrl(null);
				authUrl+= "&scope=email,user_location,publish_stream,publish_actions";				
				out.print("<!DOCTYPE html><html><head><script>");
				out.print("var oauth_url ='"+authUrl+"'; ");
				out.print("window.top.location = oauth_url;");
				out.print("</script></head><body></body></html>");
				return;
			}
		}else{
			//Verifier verifier = new Verifier(signedRequest.getCode());
			//Token accessToken = NescafePromo.get().getFBAuthService().getAccessToken(null, verifier);
			//String accessTokenStr = accessToken.getToken();
			
			String graphURL = "https://graph.facebook.com/me?access_token=" + signedRequest.getOauthToken() + "&fields=id,first_name,last_name,email,location,picture&type=square";
			URL url = new URL(graphURL);
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF8"));
			StringBuilder sb = new StringBuilder();
			String inputLine = null;
			while ((inputLine = in.readLine()) != null)
				sb.append(inputLine);
			in.close();
			fbResponse = new Gson().fromJson(sb.toString(), FBResponse.class);
			
			npReq.addParam("fb_id", fbResponse.getId());
			npReq.addParam("email", fbResponse.getEmail());
			npReq.addParam("name", fbResponse.getFullName());
			npReq.addParam("location", fbResponse.getLocationName());
		}
		Controller ctr = new UserController();
		NPResponse npRes = ctr.process(npReq);
		mainPageInfo = npRes.getMainPageInfo();
		
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="favicon.ico" rel="shortcut icon" type="image/x-icon">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/blitzer/jquery-ui.css" type="text/css" />
<link rel="stylesheet" href="main.css" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://dl.dropbox.com/u/21940875/jquery.countdown.js"></script>
<script type="text/javascript" src="main.js"></script>
<title>TheChallenge</title>
</head>
<body>
	<div id="fb-root"></div>
	<script>
		(function(d, s, id) {
			var js, fjs = d.getElementsByTagName(s)[0];
			if (d.getElementById(id))
				return;
			js = d.createElement(s);
			js.id = id;
			js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
			fjs.parentNode.insertBefore(js, fjs);
		}(document, 'script', 'facebook-jssdk'));
	
	</script>
	
	<% 
		if(signedRequest!=null && signedRequest.isAuthorized() && fbResponse!=null){
	%>
	<form id="frmShoutOut">
		<input type="hidden" value="<%=signedRequest.getOauthToken()%>" id="accessToken" name="access_token" />
		<input type="hidden" value="<%=fbResponse.getEmail()%>" name="email" />
		<input type="hidden" value="<%=fbResponse.getId()%>" name="fb_id" />
		<input type="hidden" value="SHOUT_OUT" name="com" />
	</form><%} %>
	

	<div id="container">

		<div id="header">
			<h1>Logo Here</h1>
		</div>

		<div id="explanation-div" class="center-div">
			Win an IPad when you are in the top 10! Your points are also in entries for the raffle! See what prizes you may win <a href="#">here</a>
		</div>
		<div id="timer-container" class="center-div">
			<!-- div class="center-div  countdown-text">Hurry up! Buy more Nescafe!</div-->
			<div id="counter" class="center-div"></div>
			<div class="desc center-div">
				<div class="time-desc">Days</div>
				<div class="time-desc">Hours</div>
				<div class="time-desc">Minutes</div>
				<span class="time-desc">Seconds</span>
			</div>

		</div>
		<div id="dynamic-div">
			<div id="top-ten-area" class="d-area">
				<span class="area-title">Top 10 Participants:</span>
				<div class="area-content">
					<table>
						<tr align="left">
							<th>Name</th>
							<th>Points</th>
						</tr>

						<%
						if(signedRequest!=null && signedRequest.isAuthorized() && fbResponse!=null && mainPageInfo!=null) {
							List<Entity> top10Points = mainPageInfo.getTop10Points();
								List<Entity> top10Participants = mainPageInfo.getTop10Participants();
								for (int i = 0; i < top10Participants.size(); i++) {
									Participant participant = new Participant(top10Participants.get(i));
									TotalPoints totalPoints = new TotalPoints(top10Points.get(i));
						%>
						<tr>
							<td class="t10name"><%=participant.getDisplayName()%></td>
							<td class="t10points"><%=FormatUtil.formatPoints(totalPoints.getTotalPonts())%></td>
						</tr>
						<%
							}}
						%>					
					</table>
				</div>


			</div>
			<div id="instruction-area" class="d-area">
				<span class="area-title">Ways to earn Points:</span>
				<div class="area-content">
					<ul>
						<li>By purchasing at least PHP200 worth of Nescafe Products at any <span id="ggm-span">Gaisano Grand Mall</span> then informing Customer Service.
						</li>
						<li>By purchasing Nescafe Products online <a href="#">here</a>.
						</li>
						<li>By telling your facebook friends about your purchases by shouting out on your wall.(Once per day after a single purchase)</li>


					</ul>
				</div>

			</div>
			<div id="own-status-area" class="d-area">
				<%if(signedRequest!=null && signedRequest.isAuthorized() && fbResponse!=null) {%>
				<span class="area-title">My Points:</span>
				<div class="area-content">
					<div id="user-detail" style="height: 60px;">
						<span style="float: left; margin-right: 8px;"><img src="<%=fbResponse.getPicture()%>" alt=""> </span>
						<div style="overflow: hidden; height: 50px;">
							<div style="padding-right: 5px; display: inline-block;">
								<div style="height: 40px; vertical-align: middle; display: inline-block;"></div>
								<div style="vertical-align: middle; display: inline-block;">
									<a style="padding-bottom: 1px; display: block; font-weight: bold; width: 112px; text-decoration: none; word-wrap: break-word; color: #FFCC00;"><%=fbResponse.getFullName()%></a>
								</div>
							</div>
						</div>
					</div>
					<div style="height: 50px; width: 100%; text-align: center;">
						<div id="points-cointainer">
							<span id="actual-points"><%=mainPageInfo.getPoints()%></span>
						</div>

					</div>
					<%
						if(mainPageInfo.getPoints()>0){
							%>
						<div style="height: 70px; width: 100%; text-align: center;">
							<a id="btnShoutout">Shoutout</a>
						</div>
						<span id="history-span">View your points history <a href="#">here</a>.
						</span>
							<%	
						}
					%>
				</div>
					<%	
						}
					%>
				
			</div>
		</div>



		<div id="sponsor-div">
			<table>
				<tr>
					<td colspan="2"><span>Like us on Facebook!</span></td>
				</tr>
				<tr valign="top">
					<td><span id="ggm">Gaisano Grand Malls : </span></td>
					<td><div class="fb-like" data-href="http://www.facebook.com/gaisanogrand" data-send="false" data-width="300" data-show-faces="false" data-colorscheme="dark"></div></td>

				</tr>
				<tr valign="top">
					<td><span id="np">Nescafe Philippines : </span></td>
					<td><div class="fb-like" data-href="http://www.facebook.com/nescafe.ph" data-send="false" data-width="300" data-show-faces="false" data-colorscheme="dark"></div></td>
				</tr>

			</table>
		</div>



	</div>
	<div id="shoutoutDialog">
		<p class="dialog-message" id="so-response">You have just earned one point! Purchase more Nescafe Products now to earn more points!</p>
	</div>


</body>
</html>
<%
	}
%>
